import requests
import json
import os
from threading import Thread
from src.utils.config import config


class DingdingMessager:
    def __init__(self):
        self.message_url = config.get_config('dingding', 'robot')
        self.headers = {
            "Content-Type": "application/json"
        }
        self.form_data = {
            "isAtAll": "false",
            "expire": "30",
            "robot": config.get_config('dingding', 'robot'),
            'title': '[价格]模型监控',
            "md": "true"
        }
    def async(f):
        def wrapper(*args, **kwargs):
            thr = Thread(target=f, args=args, kwargs=kwargs)
            thr.start()

        return wrapper

    @async
    def send_message(self, message):
        form_data = self.form_data.copy()
        server = os.environ.get('API_SERVER_INFO')
        env = 'test' if os.environ.get('environment') is None else os.environ.get('environment')
        msg = "## [{}价格]模型监控！\nskulevel详情："
        msg = msg.format(env)+message
        if server is not None:
            msg = msg + '  \nFrom Price Model server@{}'.format(server)
        if os.environ.get('environment') == 'deploy':
            # product环境
            form_data['message'] = msg
        else:
            # 测试环境在message前后加入"测试"字样
            msg = msg
            form_data['message'] = msg
        data={"msgtype": "markdown", "markdown": {"title": "[价格]模型监控", "text": ""}}
        data['markdown']['text'] = msg
        requests.post(self.message_url, headers=self.headers,
                      data=json.dumps(data), timeout=5)


dingding_messager = DingdingMessager()
